package com.tj.collection.aop;

import com.alibaba.fastjson.JSONObject;
import com.tj.collection.aop.anno.LogEvent;
import com.tj.collection.common.RequestLocalInfo;
import com.tj.collection.db.dao.AdminOperationLogDao;
import com.tj.collection.db.entity.AdminOperationLogEntity;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
public class DoLogAop {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    AdminOperationLogDao adminOperationLogDao;


    @Around("@annotation(logEvent)")
    public Object doLog(ProceedingJoinPoint pjp, LogEvent logEvent) throws Throwable {
        try {
            final Long adminId = RequestLocalInfo.getCurrentAdmin().getId();
            final Object[] args = pjp.getArgs();
            AdminOperationLogEntity logEntity = new AdminOperationLogEntity();
            logEntity.setAdminId(Integer.parseInt(String.valueOf(adminId)));
            logEntity.setCode(logEvent.name());
            logEntity.setContent(JSONObject.toJSONString(args));
            adminOperationLogDao.insert(logEntity);
        } catch (Exception e) {
            logger.error("====doLogError, logEvent:{}", logEvent, e);
        }

        return pjp.proceed();
    }


}